package com.lemo.juc;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteDemo {
	
	public static void main(String[] args) {
		RwDemo rwDemo =new RwDemo();
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				rwDemo.write(333);
			}
		},"Write").start();
		
		
		for (int i = 0; i < 200; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					rwDemo.read();
				}
			},"Read").start();
		}
	}
}

class RwDemo {
	private int num = 0;
	private ReadWriteLock lock = new ReentrantReadWriteLock();

	public void read() {
		lock.readLock().lock();
		try {
			System.out.println(Thread.currentThread().getName() + ":" + num);
		} finally {
			lock.readLock().unlock();
		}
	}

	public void write(int num) {
		lock.writeLock().lock();
		try {
			System.out.println(Thread.currentThread().getName() + ":" + num);
			this.num = num ;
		} finally {
			lock.writeLock().unlock();
		}
	}

}